package com.pjbao.Service.user.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pjbao.Service.user.dao.UserRepository;
import com.pjbao.Service.user.model.User;
import com.pjbao.Service.user.service.LoginAndOutService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * Created by zero on 2016/10/1.
 */
@RestController
@RequestMapping("/user")
public class LoginOutController {
    @Autowired
    LoginAndOutService loginAndOutService;
    @Autowired
    UserRepository userRepository;
    @Autowired
    RedisTemplate redisTemplate;
    ObjectMapper mapper = new ObjectMapper();

    Logger logger = LoggerFactory.getLogger("报表系统--微信绑定token验证:");
    @PostMapping("/login")
    public String login(HttpServletRequest request, User user) {
        String result="";
        return result;
    }

    @RequestMapping("/welogin")
    public String weLogin(String wechatname) {
        String result = "";
        System.out.println("获取到的微信用户名:"+wechatname);
        User us = new User();
        us = userRepository.findByWechatname(wechatname);
        if(us != null){
        result = us.getToken();
        }else{
        result = "no";
        }
        return result;
    }
    @RequestMapping("/signtoken")
    public String weSign(String wechatname,String token) {
        String result = "yes";
        logger.info("参数是wech:"+wechatname+"==token:"+token);
        User us = userRepository.findByToken(token);
        if(us!=null){
            if(us.getWechatname()==null||us.getWechatname().length()<5){
                us.setWechatname(wechatname);
                userRepository.save(us);
                result = "yes";
            }else if(!wechatname.equals(us.getWechatname())){
                result = "other";
            }
        }else{
            result = "no";
        }
        return result;
    }

    @RequestMapping("/logout")
    public String weLogout(String wechatname) {
        String result = "yes";
        User us = userRepository.findByWechatname(wechatname);
        if(us!=null){
            us.setWechatname("");
            userRepository.save(us);
            result = "yes";
        }else{
            result = "no";
        }
        return result;
    }

}
